package com.dudu.timer;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;






import com.dudu.access.RedisUtil;
import com.dudu.access.RongLianUtils;
import com.dudu.access.TianRunUtil;
import com.dudu.access.TianYiUtil;
import com.dudu.access.YonYouUtil;
import com.dudu.bean.ResponseSendVoiceBean;
import com.dudu.bean.SessionIdBean;
import com.dudu.dao.PushNoticeInfoDao;
import com.dudu.dao.SendNoticeDao;
import com.dudu.dao.SessionIDDao;
import com.dudu.dao.UploadFileDao;
import com.dudu.enumeration.AbilityTypeEnum;
import com.dudu.model.PushNoticeInfo;
import com.dudu.model.SendNotice;
import com.dudu.model.UploadFileModel;
import com.dudu.utils.DictionaryUtils;
import com.dudu.utils.EnumUtility;
import com.dudu.utils.HttpRequest;

import core.CoreDao;

/**
 * 开始定时发送语音短信任务线程 通过获取表中的数据然后调用IMS接口发送语音通知
 * 
 * @author gaoxs
 * 
 */
public class SendVoiceThread extends Thread {

    private static final Logger log = core.util.Logger.getLogger(SendVoiceThread.class.getSimpleName());
    private final String RongLianTicketUrl = DictionaryUtils.getValueByTypeAndKey("url", "RongLianTicket");
    private final String TianYiTicketUrl = DictionaryUtils.getValueByTypeAndKey("tianYi", "TianYiTicket");
    private CoreDao dao = null;
    private SendNotice mSendNotice = null;
    private SendNoticeDao mSendNoticeDao = new SendNoticeDao();
    private UploadFileDao uploadfileDao = new UploadFileDao();
    private PushNoticeInfoDao mPushNoticeInfoDao = null;
    private SessionIDDao sessionIdDao = new SessionIDDao();

    // private UploadFileDao uploadfileDao=new UploadFileDao();
    public SendVoiceThread(CoreDao dao, SendNotice sendNotice, PushNoticeInfoDao pushNoticeInfoDao) {
	this.dao = dao;
	mSendNotice = sendNotice;
	mPushNoticeInfoDao = pushNoticeInfoDao;
    }

    @Override
    public void run() {
	ResponseSendVoiceBean result = new ResponseSendVoiceBean();
	log.info("语音通知发送开始--" + mSendNotice.getSession_id());
	String fileFullName="";
	if(StringUtils.isNotBlank(mSendNotice.getMediaName())){
	    UploadFileModel fileModel = uploadfileDao.queryFileInfoBymediaName(dao, mSendNotice.getMediaName());
	    fileFullName=fileModel.getFileFullName();
	}
	if (isNullForVoiceName(mSendNotice.getVoice_type(), mSendNotice.getVoice_name(), mSendNotice.getMediaName())) {
	    log.info("语音文件还未上传成功,id=" + mSendNotice.getSession_id());
	    result.setResult("999");// 语音文件还未上传成功
	    mSendNotice.setSend_count(3);
	} else {
	    if (mSendNotice.getVoice_type().startsWith("YonYou")) {
		
		// 自建平台语音通知
		String repeat = "3";
		if (mSendNotice.getVoice_type().contains("70") || mSendNotice.getVoice_type().contains("140")) {
		    repeat = "1";
		}
		result = YonYouUtil.VoiceNotice(mSendNotice.getCaller(), mSendNotice.getCallee(), fileFullName, mSendNotice.getContent(),
			mSendNotice.getDisplayNumber(), "", "", mSendNotice.getTts_content(), "1", repeat);
	    } else if (mSendNotice.getVoice_type().equals(AbilityTypeEnum.IVR_YONYOU.getKey())) {
		// 自建平台IVR外呼
		result = YonYouUtil.IvrDial(mSendNotice.getCaller(), mSendNotice.getCallee(), mSendNotice.getDisplayNumber(), fileFullName,
			mSendNotice.getContent(), mSendNotice.getTts_content());
	    } else if (mSendNotice.getVoice_type().startsWith("TianRun")) {
		// 天润融通语音通知
		result = TianRunUtil.voiceNotice(mSendNotice.getCallee(), mSendNotice.getContent(), mSendNotice.getDisplayNumber(), "", mSendNotice.getTts_content());
	    } else if (mSendNotice.getVoice_type().startsWith("RongLian")) {
		// 荣联语音通知
		result = SendRongLianVoiceNotice(mSendNotice);
	    } else if (mSendNotice.getVoice_type().equals(AbilityTypeEnum.IVR_RONGL.getKey())) {
		// 荣联IVR语音通知
		result = RongLianUtils.IvrDial(mSendNotice.getCallee(), mSendNotice.getDisplayNumber(), mSendNotice.getSchedule_send_time(), mSendNotice.getReal_send_time(), ";",
			mSendNotice.getContent(), mSendNotice.getVoice_name(), "1", RongLianTicketUrl, "1");
		// }else if
		// (mSendNotice.getVoice_type().equals(AbilityTypeEnum.VOICENOTICE3.getKey())
		// ||
		// mSendNotice.getVoice_type().equals(AbilityTypeEnum.AUDEOSEND.getKey()))
		// {
		// // IMS语音通知
		// result =
		// ImsVoiceNoticeUtils.sendVoiceNotice3(mSendNotice.getChargeNmr(),
		// mSendNotice.getChargeKey(), mSendNotice.getDisplayNumber(),
		// mSendNotice.getCallee(),
		// mSendNotice.getVoice_name(), mSendNotice.getTts_content());
		// } else if
		// (mSendNotice.getVoice_type().equals(AbilityTypeEnum.IVR_IMS.getKey()))
		// {
		// // IMS 问卷调查
		// result =
		// ImsVoiceNoticeUtils.VoiceNotice2(mSendNotice.getDisplayNumber(),
		// mSendNotice.getChargeNmr(), mSendNotice.getChargeKey(),
		// mSendNotice.getCallee(),
		// mSendNotice.getVoice_name(), mSendNotice.getContent());
		// } else if (mSendNotice.getVoice_type().startsWith("TianYi"))
		// {
		// // 天亿语音通知
		// result = SendTianYiVoiceNotice(mSendNotice);
		// } else if
		// (mSendNotice.getVoice_type().equals(AbilityTypeEnum.IVR_TianYi.getKey()))
		// {
		// // 天亿IVR语音通知
		// result = SendTianYiVoiceNotice(mSendNotice);
	    } else {
		log.info("能力配置错误，请重新配置--" + mSendNotice.getVoice_type() + ";sessionId=" + mSendNotice.getSession_id());
		result = new ResponseSendVoiceBean();
		result.setResult("999");
	    }

	    if (StringUtils.isBlank(result.getSessionid())) {
		// 调用接口失败,需要连续调用三次,三次失败后再模拟失败状态
		mSendNotice.setSend_count(mSendNotice.getSend_count() + 1);
		RedisUtil.delKey(mSendNotice.getCallee());//,调用接口失败后,删除此key
	    } else {
		// 发送成功
		mSendNotice.setSend_count(3);
	    }

	}
	log.info("cassSessionId" + result.getSessionid() + "session_id--" + mSendNotice.getSession_id());
	// 如果是因为调用接口原因发送失败，则需要重新发送
	mSendNotice.setNote(result.getResult() + "|" + result.getDesc());
	if (mSendNotice.getNote().length() > 50) {
	    mSendNotice.setNote(mSendNotice.getNote().substring(0, 48));
	}
	// 更新发送次数(send_count,note)
	mSendNoticeDao.updateSendCount(dao, mSendNotice);
	// 判断信息发送状态
	if (!result.getResult().equals("0")) {
	    log.info("语音短信发送失败--类型：" + mSendNotice.getVoice_type() + ";sessionId=" + mSendNotice.getSession_id());
	    mSendNotice.setStatus("1");
	    // 更新发送状态(status)
	    mSendNoticeDao.updateStatus(dao, mSendNotice);

	    // 设置下次发起的时间，向后延时一分钟
	    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    Date now = new Date();
	    Date nowAdd = new Date(now.getTime() + 10 * 60 * 1000);
	    String schedule_send_time = format.format(nowAdd);
	    mSendNotice.setSchedule_send_time(schedule_send_time);
	    // 更新下次发送时间(schedule_send_time)
	    mSendNoticeDao.updateSendTime(dao, mSendNotice);

	    /**
	     * 第三次发送失败时向ISV推送发送失败的结果 2016.8.11 by jack
	     */
	    if (mSendNotice.getSend_count() == 3) {
		insertPushNoticeInfo(mSendNotice, "-1", result.getDesc());
	    }
	} else {
	    log.info("语音短信发送成功--cassSessionId：" + result.getSessionid() + ";sessionId=" + mSendNotice.getSession_id());

	    mSendNotice.setStatus("0");
	    // 更新发送状态(status)
	    int statusResult = mSendNoticeDao.updateStatus(dao, mSendNotice);
	    if (statusResult > 0) {
		log.info("发送成功，将状态更新为成功" + mSendNotice.getSession_id());
	    }
	    if (StringUtils.isNotBlank(result.getSessionid())) {
		// qinfx 2017-05-23 更新t_session_id
		this.insertSessionId(mSendNotice.getSession_id(), result.getSessionid());

		/**
		 * 调用Ims接口后，立刻推送sessionid给指定url。2015.12.22修改
		 * 1）推送成功，插入表t_push_notice_info,状态为0
		 * 2）推送失败，插入表t_push_notice_info,状态为1，定时任务会再次发送
		 */
		if (!StringUtils.isEmpty(mSendNotice.getPush_url())) {
		    // 向ISV推送发送成功的结果 2016.8.11 by jack
		    insertPushNoticeInfo(mSendNotice, mSendNotice.getSession_id(), result.getDesc());
		}

	    }

	}
	mSendNotice.setRun_thread("");
	mSendNoticeDao.updateRunThread(dao, mSendNotice);
    }

    /**
     * 判断 使用语音文件发送通知或者外呼时需要先判断语音文件是否上传成功
     * 
     * @param voice_type
     * @param voice_name
     * @return
     */
    private boolean isNullForVoiceName(String voice_type, String voice_name, String mediaName) {
	// ivr与录音语音通知
	if (voice_type.indexOf("Audeo") > -1 || voice_type.startsWith("Ivr")) {
	    // 使用语音文件发送通知或者外呼时需要先判断语音文件是否上传成功
	    if (StringUtils.isBlank(voice_name) && StringUtils.isNotBlank(mediaName)) {
		return true;
	    } else {
		return false;
	    }
	} else {
	    return false;
	}
    }

    /**
     * 摸拟调用三次接口失败后推送失败状态
     * 
     * @param sendNotice
     * @param sessionId
     * @param desc
     */
    private void sendFailState(SendNotice sendNotice, String sessionId, String desc) {
	if (sessionId.equals("-1")) {
	    RedisUtil.setString("cassSessionId:" + sendNotice.getSession_id(), 30 * 60, sendNotice.getSession_id());
	    String ticketUrl = DictionaryUtils.getValueByTypeAndKey("url", "failStatusUrl");
	    // 调用三次接口失败后推送失败状态
	    StringBuffer sb = new StringBuffer();
	    sb.append(ticketUrl);
	    sb.append("?");
	    sb.append("unique_id=" + sendNotice.getSession_id());// sessionId
	    sb.append("&status=" + "21");
	    sb.append("&statusReason=" + "摸拟失败状态," + desc);
	    sb.append("&clid=" + sendNotice.getDisplayNumber());
	    sb.append("&customerNumber=" + sendNotice.getCallee());
	    String ret = HttpRequest.getData(sb.toString());
	    log.info("摸拟调用三次接口失败后推送失败状态 ret=" + ret);
	}
    }

    /**
     * 向用户推送结果 1）推送成功，插入表t_push_notice_info,状态为0
     * 2）推送失败，插入表t_push_notice_info,状态为1，定时任务会再次发送
     * 
     * @param sendNotice
     * @param sessionId
     * @param desc
     */
    private void insertPushNoticeInfo(SendNotice sendNotice, String sessionId, String desc) {
	// 摸拟调用三次接口失败后推送失败状态
	this.sendFailState(sendNotice, sessionId, desc);
	if (sendNotice != null && sessionId != null && StringUtils.isNotBlank(sendNotice.getPush_url())) {
	    PushNoticeInfo record = new PushNoticeInfo();
	    record.setPush_url(sendNotice.getPush_url());
	    record.setVoice_id(sendNotice.getMeet_ims_id());
	    record.setPhone(sendNotice.getCallee());
	    record.setSession_id(sessionId);
	    if (sessionId.equals("-1")) {
		if (getErrorMsg(desc)) {
		    record.setNote(desc);
		}
	    }
	    String ret = SendVoiceUtil.sendVoiceInfo(record);
	    String result1 = "";
	    if (StringUtils.isNotBlank(ret)) {
		try {
		    JSONObject retJson = JSONObject.fromObject(ret);
		    result1 = retJson.optString("result");
		} catch (Exception e) {
		    log.info("t_push_notice_info json格式化error:" + ret);
		}
	    }
	    record.setSend_count(1);
	    if (result1.equals("0")) {// 发送成功
		record.setStatus("0");
	    } else {// 发送失败
		record.setStatus("1");
	    }

	    // 插入数据
	    mPushNoticeInfoDao.insert(dao, record);
	}
    }

    /**
     * 存储sessionID关联关系
     * 
     * @param duduSessionId
     * @param cassSessionId
     */
    private void insertSessionId(String duduSessionId, String cassSessionId) {
	try {
	    /**
	     * sessionId关联关系存储到redis中，接收状态和话单时使用，有效期30分钟
	     * key=dudu:open:cassSessionId:2C8AE90912CBBE48EE29FD9480BD9246
	     */
	    RedisUtil.setString("cassSessionId:" + cassSessionId, 30 * 60, duduSessionId);

	    SessionIdBean bean = new SessionIdBean();
	    bean.setCass_session_id(cassSessionId);
	    bean.setDudu_session_id(duduSessionId);
	    if (-1 == this.sessionIdDao.insert(dao, bean)) {
		log.error("t_session_id保存数据失败，duduSessionId： " + duduSessionId + ", cassSessionId:" + cassSessionId);
	    }
	} catch (Exception ex) {
	    log.error("t_session_id保存数据失败，duduSessionId： " + duduSessionId + ", cassSessionId:" + cassSessionId);
	    log.error(ex.getMessage());
	    ex.printStackTrace();
	}
    }

    /**
     * 容联语音通知
     * 
     * @param mSendNotice
     * @return
     */
    public ResponseSendVoiceBean SendRongLianVoiceNotice(SendNotice mSendNotice) {
	if (EnumUtility.isBlank(mSendNotice.getTts_content())) {// 无前导音
	    return RongLianUtils.VoiceNotice(mSendNotice.getCallee(), mSendNotice.getVoice_name(), mSendNotice.getContent(), "1", mSendNotice.getDisplayNumber(),
		    RongLianTicketUrl, "");
	} else {// 有前导音
	    if (mSendNotice.getVoice_type().startsWith(AbilityTypeEnum.RONGLIANVOICE.getKey())) {
		// 荣联文字语音通知
		return RongLianUtils.VoiceNotice(mSendNotice.getCallee(), "", mSendNotice.getTts_content() + mSendNotice.getContent(), "1", mSendNotice.getDisplayNumber(),
			RongLianTicketUrl, "");
	    } else if (mSendNotice.getVoice_type().startsWith(AbilityTypeEnum.RONGLIANAUDEO.getKey())) {
		// 荣联录音语音通知
		return RongLianUtils.VoiceNotice(mSendNotice.getCallee(), mSendNotice.getVoice_name(), mSendNotice.getTts_content(), "1", mSendNotice.getDisplayNumber(),
			RongLianTicketUrl, "");
	    } else {
		ResponseSendVoiceBean result = new ResponseSendVoiceBean();
		result.setResult("999");
		result.setDesc("通道类型错误 abilityType:" + mSendNotice.getVoice_type());
		return result;
	    }
	}

    }

    /**
     * 天亿通道语音通知
     * 
     * @param mSendNotice
     * @return
     */
    public ResponseSendVoiceBean SendTianYiVoiceNotice(SendNotice mSendNotice) {
	/**
	 * 是否为青岛项目请求 70字和140字套餐为青岛项目产品
	 */
	boolean isQingDao = false;
	if (mSendNotice != null && !EnumUtility.isBlank(mSendNotice.getVoice_type()) && (mSendNotice.getVoice_type().contains("70") || mSendNotice.getVoice_type().contains("140"))) {
	    isQingDao = true;
	}
	log.info("isQingDao1:" + isQingDao);
	if (EnumUtility.isBlank(mSendNotice.getTts_content())) {
	    // 前导音为空
	    if (mSendNotice.getVoice_type().startsWith(AbilityTypeEnum.TIANYIVOICE.getKey())) {
		// 文字

		return TianYiUtil.VoiceNotice(mSendNotice.getCallee(), "", mSendNotice.getContent(), mSendNotice.getDisplayNumber(), TianYiTicketUrl, "", isQingDao);
	    } else if (mSendNotice.getVoice_type().startsWith(AbilityTypeEnum.IVR_TianYi.getKey())) {
		// 天亿IVR
		if (StringUtils.isNotBlank(mSendNotice.getVoice_name())) {
		    return TianYiUtil.IvrDial(mSendNotice.getCallee(), mSendNotice.getDisplayNumber(), "%V" + mSendNotice.getVoice_name(), "", TianYiTicketUrl, "");
		} else {
		    return TianYiUtil.IvrDial(mSendNotice.getCallee(), mSendNotice.getDisplayNumber(), "", mSendNotice.getContent(), TianYiTicketUrl, "");
		}

	    } else {
		// 语音
		return TianYiUtil.VoiceNotice(mSendNotice.getCallee(), "%V" + mSendNotice.getVoice_name(), "", mSendNotice.getDisplayNumber(), TianYiTicketUrl, "", isQingDao);
	    }

	} else {
	    // 有前导音
	    if (mSendNotice.getVoice_type().startsWith(AbilityTypeEnum.TIANYIVOICE.getKey())) {
		// 文字
		String content = "%C" + mSendNotice.getTts_content() + "|%C" + mSendNotice.getContent();
		return TianYiUtil.VoiceNotice(mSendNotice.getCallee(), content, "", mSendNotice.getDisplayNumber(), TianYiTicketUrl, "", isQingDao);
	    } else if (mSendNotice.getVoice_type().startsWith(AbilityTypeEnum.IVR_TianYi.getKey())) {
		// 天亿IVR
		String content = "%C" + mSendNotice.getTts_content();
		if (StringUtils.isNotBlank(mSendNotice.getVoice_name())) {
		    content = content + "|%V" + mSendNotice.getVoice_name();
		} else {
		    content = content + "|%C" + mSendNotice.getContent();
		}
		return TianYiUtil.IvrDial(mSendNotice.getCallee(), mSendNotice.getDisplayNumber(), content, "", TianYiTicketUrl, "");
	    } else {
		// 语音
		String content = "%C" + mSendNotice.getTts_content() + "|%V" + mSendNotice.getVoice_name();
		return TianYiUtil.VoiceNotice(mSendNotice.getCallee(), content, "", mSendNotice.getDisplayNumber(), TianYiTicketUrl, "", isQingDao);
	    }
	}
    }

    /**
     * 错误处理
     * 
     * @param desc
     * @return
     */
    public boolean getErrorMsg(String desc) {
	List<String> errorMsg = new ArrayList();
	errorMsg.add("号码格式错误");
	errorMsg.add("呼叫限制");
	errorMsg.add("敏感字");
	errorMsg.add("非法号码");
	errorMsg.add("电话号码位数不足");
	errorMsg.add("同一号码呼叫");
	errorMsg.add("电话号码存在非法字符");
	for (String error : errorMsg) {
	    if (desc.contains(error)) {
		return true;
	    }
	}
	return false;
    }
}
